package com.shujia.mr.kqzl2;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;

import java.io.IOException;

//<0L,"20180603-1001	50">   -->  <"1001","$20180603-50">
//<0L,"1001,万寿西宫,北京">      -->  <"1001","#北京-万寿西宫">

//reduce输入: <"1001",["$20180603-50","#北京-万寿西宫"]>   <"3033",["$20180603-50"]>
//reduce输出: <"20180603-北京-万寿西宫","50">


public class PM25JoinCityMapper extends Mapper<LongWritable, Text, Text, Text> {
    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, Text>.Context context) throws IOException, InterruptedException {
        //判断改行数据是来自于哪一个文件的
        //context hadoop上下文环境
        //通过context获取该行数据来自于哪一个切片
        FileSplit inputSplit = (FileSplit) context.getInputSplit();
        String fileName = inputSplit.getPath().getName();
        String line = value.toString();
        //根据文件的名字判断该行数据是什么类型的数据
        if (fileName.startsWith("city") && !line.startsWith("id")) {
            //该行数据是城市数据
            //<0L,"1001,万寿西宫,北京">
            String[] infos = line.split(",");
            if(infos!=null){
                context.write(new Text(infos[0]), new Text("#" + infos[2] + "-" + infos[1]));
            }
        } else if (fileName.startsWith("part")) {
            //该行数据是平均值数据
            //<0L,"20180603-1001	50">
            String[] infos = line.split("\t");
            String[] strings = infos[0].split("-");// 20180603-1001
            String date = strings[0];
            String id = strings[1];
            String avg_pm25 = infos[1];// 50
            context.write(new Text(id), new Text("$" + date + "-" + avg_pm25));
        }
    }
}
